package org.example.web;


import com.example.fanqie.entity.Novel;
import com.example.fanqie.entity.User;
import com.example.fanqie.mapper.NovelMapper;
import org.example.util.uploadUtil;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/novel")
public class novelDao {


    @Resource
    private NovelMapper novelMapper;



    @Resource
    private uploadUtil uploadUtil;



    @RequestMapping("upImg")
    public String upImg(@RequestBody MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return "上传文件内容为空，请重新选择";
        }

        //获取上传文件的原始文件名，将其赋值给变量 filename。
        String filename = file.getOriginalFilename();
        //找到文件名中最后一个点（.）的索引位置，然后使用 substring 方法截取从该位置开始到字符串末尾的子字符串，即获取文件后缀名部分。
        String suffix = filename.substring(filename.lastIndexOf("."));
        String newFilename = UUID.randomUUID()+suffix;

        String uploadadd = uploadUtil.uploadadd(file);
        return uploadadd;


    }


    @RequestMapping("add")
    public int addNovel(@RequestBody Novel novel) {
        int insert = novelMapper.insert(novel);


        return  insert;

    }

    @RequestMapping("select")
    public List<Novel> selectnovel(  ){

        List<Novel> users = novelMapper.selectnovel();

        return users;
    }


    //根据作者 和  小说类型  查询
    @RequestMapping("selectlist")
    public List<Novel> selectlist( @RequestBody Novel  novel ){

        //作者 和 小说类型 有一个为空
        if(novel.getAuthorId() == null || novel.getCategoryId() == null){
            List<Novel> novels = novelMapper.selecttiaojian01(novel.getAuthorId() ,novel.getCategoryId());

            return novels;
        }
        //作者 和 小说类型都不为空
        List<Novel> novels = novelMapper.selecttiaojian02(novel.getAuthorId() ,novel.getCategoryId());

        return novels;
    }


    @RequestMapping("delete")
    public int deleteNovel( @RequestBody Novel novel){

        int delete = novelMapper.updateById(novel);

        return delete;
    }

    @RequestMapping("selectnovelId")
    public Novel selectnovelId( @RequestBody Novel novel){

        Novel novels = novelMapper.selectnovelId(novel.getNovelId());
        System.out.println(novels);

        return novels;

    }

    @RequestMapping("update")
    public int updateNovel( @RequestBody Novel novel){
        int update = novelMapper.updateById(novel);

        return update;
    }




}
